package com.qf.electronic.mall.mail.service.handler;

import com.qf.constant.RabbitmqConstant;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 作者：张健
 * 项目名：electronic-mall
 * 时间：2020/3/11  20:12
 * 描述：
 */
@Component
public class MailHandler {

    @Autowired
    private JavaMailSender sender;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${activeServerUrl}")
    private String activeServerUrl;

    @RabbitListener(queues = RabbitmqConstant.MAIL_SEND_QUEUE)
    public void sendMail(String data)  {
        MimeMessage message = sender.createMimeMessage();

        MimeMessageHelper mailMessage = null;
        try {
            mailMessage = new MimeMessageHelper(message, true);
            mailMessage.setSubject("请您激活商城账号");

            //读取模板内容

            Context context = new Context();
            String mail=data.split(":")[0];
            String uuid=data.split(":")[1];
            context.setVariable("username",mail);
            context.setVariable("url",activeServerUrl+uuid);
            String info=templateEngine.process("emailTemplate",context);

            mailMessage.setText(info,true);

            mailMessage.setFrom("527802877@qq.com");

            mailMessage.setTo(mail);

            sender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
}
